package net.dgg.zz.common.service;

import net.dgg.iboss.base.util.CustomerNumberEncryptionUtil;
import net.dgg.iboss.base.util.DesUtil;
import net.dgg.tmd.foundation.platform.common.util.TranslateUtil;
import net.dgg.tmd.foundation.platform.session.SessionManager;
import net.dgg.zz.common.base.service.BaseService;
import net.dgg.zz.common.constant.ScProductConstant;
import net.dgg.zz.common.dao.ProductDao;
import net.dgg.zz.common.entity.OrderProductVo;
import net.dgg.zz.common.entity.Product;
import net.dgg.zz.common.utils.StringUtils;
import net.dgg.zz.common.utils.ValidateUtils;
import net.dgg.zz.credential.excption.CertificateExcption;
import net.dgg.zz.production.entity.ProductOrder;
import net.dgg.zz.production.inProcess.dao.ProductOrderDao;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 销售子订单
 */
@Service
public class ProductService extends BaseService {
    @Resource
    private ProductDao productDao;

    @Resource
    private ProductOrderDao productOrderDao;
    @Resource
    private CommonService commonService;
    @Resource
    private SessionManager sessionManager;
    @Resource
    private TranslateUtil translateUtil;
    @Resource
    private DesUtil desUtil;

    /**
     * 查询销售子订单信息（分页）
     *
     * @return list
     * @Param params
     */
    public List<OrderProductVo> findWaitAddCredentailProductWithPage(Map params) {
        if (null == params.get("orderColumn")) {
            params.put("orderDir", "desc");//排序方向
            params.put("orderColumn", "p.create_time");//排序的列
        }
        if (params.containsKey("isAll") && params.get("isAll").equals("0")) {
            params.put("signOrgId", commonService.findUserSyb(sessionManager.getCurrentUser()));
        }
        if (params.containsKey("contactPhone") && StringUtils.isNotEmpty(params.get("contactPhone"))) {
            params.put("contactPhone", desUtil.encrypt(params.get("contactPhone").toString()));
        }
        List<OrderProductVo> orderProducts = productDao.queryOrderProductVoWithPage(params);
        String[] column = {"costState", "payMethod"};
        orderProducts = translateUtil.translateList(column, orderProducts);
        String[] hideColum = {"customerPhone","contactPhone"};
        orderProducts = desUtil.decryptList(hideColum, orderProducts);
        orderProducts = CustomerNumberEncryptionUtil.encryptionList(hideColum, orderProducts);
        return orderProducts;
    }

    /**
     * 查询销售子订单信息
     *
     * @return list
     * @Param params
     */
    public List<OrderProductVo> findWaitAddCredentailProduct(Map params) {
        List<OrderProductVo> orderProducts = productDao.queryOrderProductVo(params);
        return orderProducts;
    }

    /**
     * 验证销售子订单状态是否可以新增证书（同时验证生产订单状态）
     *
     * @param params
     */
    public OrderProductVo checkProduct(Map params) {
        List<OrderProductVo> orderProducts = productDao.queryOrderProductVo(params);
        // 证书关联订单不存在或者存在多个
        ValidateUtils.isTrue(StringUtils.isNotEmpty(orderProducts) && orderProducts.size() == 1, CertificateExcption.class, "该销售子订单信息有误，请核对！");

        OrderProductVo orderProductVo = orderProducts.get(0);

//        // 验证证书关联销售订单状态,如果没有支付则不能进行证书新增
//        ValidateUtil.isTrue(StringUtils.isNotEmpty(orderProductVo.getCostState()) && orderProductVo.getCostState().equals(ScProductConstant.ALREADY_PAY), CertificateExcption.class, "该销售子订单未进行费用申请或费用申请审核未通过，不能新增证书！");

        // 查询该销售子订单绑定的生产订单
        ProductOrder productOrder = productOrderDao.selectByPrimaryKey(orderProductVo.getScProductOrderId());

        //查询生产订单的状态是否能否新增证书
        ValidateUtils.isTrue(StringUtils.isNotEmpty(productOrder) && !productOrder.getStatus().equals(ScProductConstant.SC_ORDER_OVER_CERTIFICATE), CertificateExcption.class, "该销售子订单绑定的生产订单已完结，证书已经入库！");

        return orderProducts.get(0);
    }

    /**
     * 订单插入接口
     *
     * @param product
     * @return
     */
    public int iboosInsertProduct(Product product) {
        return productDao.iboosInsertSelective(product);
    }
    /**
     * 订单插入接口-企大宝
     *
     * @param product
     * @return
     */
    public int iboosInsertProductQdb(Product product) {
        return productDao.iboosInsertSelectiveQdb(product);
    }
    /**
     * 根据销售子订单id查询
     *
     * @param orderId
     * @param i
     * @return
     */
    public Product findProductByOrderId(Long orderId, Integer i) {
        Map map = new HashMap();
        if (i != null){
            map.put("scProductOrderId", orderId);
        } else {
            map.put("orderId", orderId);
        }
        return productDao.findProductByOrderId(map);
    }

    /**
     * 根据销售子订单表的id查询
     *
     * @param id
     * @return
     */
    public Product selectByPrimaryKey(Long id) {
        return productDao.selectByPrimaryKey(id);
    }

    /**
     * 修改销售子订单
     *
     * @param product
     */
    @Transactional
    public void updateProduct(Product product) {
        productDao.updateByPrimaryKeySelective(product);
    }

    /**
     * 删除销售子订单
     *
     * @param orderBusinessId
     * @return
     */
    @Transactional
    public Product delProduct(Long orderBusinessId) {
        Product product = findProductByOrderId(orderBusinessId, null);
        ValidateUtils.isTrue(StringUtils.isNotEmpty(product), CertificateExcption.class, "销售子订单不存在，请核对后进行操作！");

        // 如果销售子订单已经绑定了证书
        ValidateUtils.isTrue(product.getRelevanceCredential().intValue() != 1, CertificateExcption.class, "该销售子订单已经绑定了证书，不能进行删除！");
        ValidateUtils.isTrue(product.getRelevanceCredential().intValue() != 2, CertificateExcption.class, "该销售子订单已删除，不能进行重复删除！");
        product.setRelevanceCredential(2);
        updateProduct(product);

        // 验证证书关联的生产订单状态
        ProductOrder productOrder = productOrderDao.selectByPrimaryKey(product.getScProductOrderId());
        ValidateUtils.isTrue(StringUtils.isNotEmpty(productOrder) && !productOrder.getStatus().equals(ScProductConstant.SC_ORDER_OVER_CERTIFICATE), CertificateExcption.class, "该销售子订单绑定的生产订单已完结，证书已经入库！");
        // 同步生产订单状态为完结
        commonService.updateScProductOrderStatus(product.getScProductOrderId());

        return product;
    }

    /**
     * 通过productId查询订单产品详情
     * @param productId productId
     * @return 返回值
     */
    public OrderProductVo selectOrderProductVoByProductId(Long productId) {
        return productDao.selectOrderProductVoByProductId(productId);
    }
}
